import React from 'react'
import './App.css'
class App extends React.Component {
  constructor() {
    super()
    this.state = {
      i: 0,
      size: 3,
    }
  }
  componentDidMount() {
    this.start()
  }
  data = [
    {
      id: 0,
      pic: 'url(' + require('./images/1.jpg') + ')',
    },
    {
      id: 1,
      pic: 'url(' + require('./images/2.jpg') + ')',
    },
    {
      id: 2,
      pic: 'url(' + require('./images/3.jpg') + ')',
    },
  ]
  render() {
    return (
      <div className="shell">
        <ul className="images" style={{ left: this.state.i * -100 + '%' }}>
          {this.data.map((item) => (
            <li
              key={item.id}
              className="img"
              style={{ backgroundImage: item.pic }}></li>
          ))}
        </ul>
        <ul className="min-images">
          {this.data.map((item) => (
            <li
              key={item.id}
              style={{ backgroundImage: item.pic }}
              // 点击绑定事件，传入点击的索引
              onClick={() => this.handleClick(item.id)}
              className={this.state.i === item.id ? 'active' : 'min'}></li>
          ))}
        </ul>
        <div className="button">
          <div className="button-left" onClick={() => this.sub()}>
            &lt;
          </div>
          <div className="button-right" onClick={() => this.add()}>
            &gt;
          </div>
        </div>
      </div>
    )
  }

  handleClick(index) {
    this.stop()
    this.setState(
      {
        i: index,
      },
      () => {
        // 异步方法用回调函数
        this.start()
      }
    )
  }

  add() {
    this.stop()
    let ad = this.state.i
    // 拒绝在setState方法中引入state，所以逻辑需要写在外面再赋值
    if (ad >= this.state.size - 1) {
      ad = 0
    } else {
      ad = ad + 1
    }
    this.setState(
      {
        i: ad,
      },
      () => {
        // 异步方法用回调函数
        this.start()
      }
    )
  }

  sub() {
    this.stop()
    let sb = this.state.i
    if (sb <= 0) {
      sb = this.state.size - 1
    } else {
      sb = sb - 1
    }
    this.setState(
      {
        i: sb,
      },
      () => {
        // 异步方法用回调函数
        this.start()
      }
    )
  }
  start() {
    this.timer = setInterval(() => {
      // 自加
      let b = this.state.i
      if (b >= this.state.size - 1) {
        b = 0
      } else {
        b = b + 1
      }
      this.setState({
        i: b,
      })
    }, 3000)
  }
  stop() {
    this.timer && clearInterval(this.timer)
  }
}

export default App
